package com.wb.test;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.mapper.ObjectMapper;

/**
 * @author wb
 * @date 2025/1/17 13:48
 */
public class InsertDoc {

    public static void main(String[] args) {
        ConnectElasticsearch.connect(client -> {
//            // 新增文档 - 请求对象
//            IndexRequest request = new IndexRequest();
//            // 设置索引及唯一性标识
//            request.index("user").id("1001");
//
//            // 创建数据对象
//            User user = new User();
//            user.setName("zhangsan");
//            user.setAge(30);
//            user.setSex("男");
//
//
//
////            ObjectMapper objectMapper = new ObjectMapper();
////            String productJson = objectMapper.writeValueAsString(user);
//            String userJson = JSON.toJSONString(user);
//            // 添加文档数据，数据格式为 JSON 格式
//            request.source(userJson, XContentType.JSON);
//            // 客户端发送请求，获取响应对象
//            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//            //3.打印结果信息
//            System.out.println("_index:" + response.getIndex());
//            System.out.println("_id:" + response.getId());
//            System.out.println("_result:" + response.getResult());



            //批量新增
            //创建批量新增请求对象
            BulkRequest request = new BulkRequest();
            request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name","zhangsan"));
            request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name","lisi"));
            request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name","wangwu"));
            //客户端发送请求，获取响应对象
            BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
            //打印结果信息
            System.out.println("took:" + responses.getTook());
            System.out.println("items:" + responses.getItems());


        });
    }
}

